package com.link.play.fit.ai.ui.view

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.animation.LinearInterpolator
import androidx.appcompat.widget.AppCompatTextView
import com.link.play.fit.ai.R

class ProgressTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private var animator: ValueAnimator? = null
    private var currentProgress = 1
    private var minDuration = 3000L // 默认最小3秒
    private var maxDuration = 5000L // 默认最大5秒

    init {
        // 初始化显示1%
        text = "1%"

        // 从XML属性读取配置（可选）
        context.theme.obtainStyledAttributes(
            attrs,
            R.styleable.ProgressTextView,
            0, 0
        ).apply {
            try {
                minDuration = getInt(R.styleable.ProgressTextView_minDuration, 3).toLong() * 1000
                maxDuration = getInt(R.styleable.ProgressTextView_maxDuration, 5).toLong() * 1000
            } finally {
                recycle()
            }
        }
    }

    // 开始动画
    fun startProgressAnimation() {
        stopProgressAnimation() // 先停止之前的动画

        animator = ValueAnimator.ofInt(1, 99).apply {
            duration = (minDuration..maxDuration).random()
            interpolator = LinearInterpolator()

            addUpdateListener { animation ->
                currentProgress = animation.animatedValue as Int
                text = "$currentProgress%"
            }

            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator) {
                    text = "99%"
                }
            })

            start()
        }
    }

    // 取消动画（可恢复初始状态）
    fun stopProgressAnimation(resetToStart: Boolean = true) {
        animator?.cancel()
        animator = null
        if (resetToStart) {
            text = "1%"
        }
    }

    // 防止内存泄漏
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        stopProgressAnimation(resetToStart = false)
    }
}